/*
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef RTP_H_
#define RTP_H_

#include <stdint.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#include "rtsp_log.h"

#undef FRAME_DATA_DEBUG

struct RtpHeader
{
    /* byte 0 */
    uint8_t csrcLen:4;
    uint8_t extension:1;
    uint8_t padding:1;
    uint8_t version:2;

    /* byte 1 */
    uint8_t payloadType:7;
    uint8_t marker:1;
    
    /* bytes 2,3 */
    uint16_t seq;
    
    /* bytes 4-7 */
    uint32_t timestamp;
    
    /* bytes 8-11 */
    uint32_t ssrc;
};

struct RtpPacket
{
    struct RtpHeader rtpHeader;
    uint8_t payload[1403];
};

class Rtp{
public:
	~Rtp()
	{
		close(saveRtpFd_);
		close(saveRingFd_);
	}

	Rtp()
	{
#ifdef FRAME_DATA_DEBUG
		saveRtpFd_ = open("/userdata/saveRtpFd_.h265" , O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
		if (saveRtpFd_ < 0){
			SAMPLE_ERROR(" open /userdata/saveRtpFd_s.h265 Error");
			while(1);
		}
		saveRingFd_ = open("/userdata/saveRingFd_.h265" , O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
		if(saveRingFd_ < 0){
			SAMPLE_ERROR(" open /userdata/saveRingFd_.h265 Error");
			while(1);
		}
#endif		
	}
	int UdpSendPacket(struct RtpPacket* rtpPacket, uint32_t dataSize);
	int UdpSendFrame(uint8_t *pNalBuf, int s32NalBufSize);
	int SetIpPort(char* ip, uint8_t ipLen, int port);
	int UdpSocket(void);
	int UdpGetSocket(void);
	int CloseUdpSocket(void);
	int saveRtpFd_ = -1;
	int saveRingFd_ = -1;
private:
	int sock_ = -1;
	int port_ = -1;
	char ip_[15] = {0};
};

#endif
